/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef GAME_SERVER_DBCSTORE_H_
#define GAME_SERVER_DBCSTORE_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <cstdint>
#include <list>
#include <boost/unordered_map.hpp>
#include "Shared/Global_Macros.h"
#include "Shared/DBC/DBCFileLoader.h"


namespace Shared {
namespace DBC {

    template<class T>
    class DBCStorage
    {
        typedef std::list<char*> StringPoolList;
    public:
        explicit DBCStorage(const char* f) 
            : _nCount(0), _fieldCount(0)
            , _format(f), _indexTable(NULL)
            , _dataTable(NULL), _data()
            , _loaded(false), _stringPoolList() { }
        ~DBCStorage() { clear(); }

        std::uint32_t  getNumRows() const { return _loaded ? _data.size() : _nCount; }
        const char* getFormat() const { return _format; }
        std::uint32_t getFieldCount() const { return _fieldCount; }

        const T* lookupEntry(std::uint32_t id) const
        {
            if (_loaded)
            {
                typename boost::unordered_map<std::uint32_t, const T*>::const_iterator it = _data.find(id);
                if (it != _data.end()) {
                    return it->second;
                }
            }
            return (id >= _nCount) ? NULL : _indexTable[id];
        }

        bool load(char const* fn)
        {
            DBCFileLoader dbc;
            // Check if load was sucessful, only then continue
            if (!dbc.load(fn, _format))
            { return false; }

            _fieldCount = dbc.getCols();

            // load raw non-string _data
            _dataTable = (T*)dbc.autoProduceData(_format, _nCount, (char**&)_indexTable);

            // load strings from dbc _data
            _stringPoolList.push_back(dbc.autoProduceStrings(_format, (char*)_dataTable));

            // error in dbc file at loading if NULL
            return _indexTable != NULL;
        }

        void setEntry(std::uint32_t id, T* t) // Cryptic they say..
        {
            if (!_loaded)
            {
                for (std::uint32_t i = 0; i < _nCount; ++i)
                {
                    T const* node = lookupEntry(i);
                    if (!node)
                        continue;
                    _data[i] = node;
                }
                _loaded = true;
            }
            _data[id] = t;
        }

        bool loadStringsFrom(const char* fn)
        {
            // DBC must be already _loaded using Load
            if (!_indexTable)
            { return false; }

            DBCFileLoader dbc;
            // Check if load was successful, only then continue
            if (!dbc.load(fn, _format))
            { return false; }

            // load strings from another locale dbc _data
            _stringPoolList.push_back(dbc.autoProduceStrings(_format, (char*)_dataTable));

            return true;
        }

        void clear()
        {
            if (_loaded)
            {
                _data.clear();
                _loaded = false;
            }

            if (!_indexTable)
            { return; }

            delete[]((char*)_indexTable);
            _indexTable = NULL;
            delete[]((char*)_dataTable);
            _dataTable = NULL;

            while (!_stringPoolList.empty())
            {
                delete[] _stringPoolList.front();
                _stringPoolList.pop_front();
            }
            _nCount = 0;
        }

        void eraseEntry(std::uint32_t id) 
        { 
            SHARED_ASSERT(id < _nCount && "Entry to be erased must be in bounds!"); 
            _indexTable[id] = NULL; 
        }
        void insertEntry(T* entry, std::uint32_t id) 
        { 
            SHARED_ASSERT(id < _nCount && "Entry to be inserted must be in bounds!");
            _indexTable[id] = entry; 
        }

    private:
        std::uint32_t _nCount;
        std::uint32_t _fieldCount;
        char const* _format;
        T** _indexTable;
        T* _dataTable;
        boost::unordered_map<std::uint32_t, const T*> _data;
        bool _loaded;
        StringPoolList _stringPoolList;
    };

}}

#endif // GAME_SERVER_DBCSTORE_H_
